//
//  SEGCompletePesonalInfoViewController.m
//  ExcellentHome
//
//  Created by 梁昆 on 2017/11/6.
//  Copyright © 2017年 陈区. All rights reserved.
//

#import "SEGEditDetailViewController.h"
#import "SEGCompletePesonalInfoViewController.h"
#import <commonThirds/SEGImagePickerManager.h>

#import "SEGCompletePesonalInfoViewModel.h"

@interface SEGCompletePesonalInfoViewController ()<UIActionSheetDelegate, UINavigationControllerDelegate, UIImagePickerControllerDelegate,SEGCompleteInfoViewDelegate,UITextFieldDelegate, SEGImagePickerManagerDelegate>

@property (nonatomic, strong) UIScrollView *aScrollView;

/*
 封装View
 */
@property (nonatomic, strong)SEGCompleteInfoView *completeView;
/*
 返回按钮
 */
@property (nonatomic, strong)UIButton *goBackBtn;
/*
 跳过按钮
 */
@property (nonatomic, strong)UIButton *passButton;
/*
 继续按钮
 */
@property (nonatomic, strong)UIButton *comtinueButton;
@property (nonatomic, strong) SEGImagePickerManager *imagePicker;

/// viewModel
@property (nonatomic, strong) SEGCompletePesonalInfoViewModel *viewModel;

@end

@implementation SEGCompletePesonalInfoViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES];
}
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:animated];
}
- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    //记录scrollview的contentsize的高度
    CGFloat line2MaxY = self.completeView.line2.frame.origin.y + self.completeView.line2.size.height;
    self.aScrollView.contentSize = CGSizeMake(LYScreenWidth(), line2MaxY + 10);
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = kColor_W;
    [self.navigationController setNavigationBarHidden:YES];

    //监控键盘的弹起和隐藏
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShowChangeFrame:)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillHideChangeFrame:)
                                                 name:UIKeyboardWillHideNotification
                                               object:nil];

    [self setupUI];
}

#pragma mark - UI
- (void)setupUI {
    self.aScrollView = [[UIScrollView alloc] init];
    self.aScrollView.showsHorizontalScrollIndicator = NO;
    self.aScrollView.showsVerticalScrollIndicator = NO;
    [self.view addSubview:self.aScrollView];
    [self.aScrollView addSubview:self.completeView];
    [self.view addSubview:self.goBackBtn];
    [self.view addSubview:self.passButton];
    [self.view addSubview:self.comtinueButton];

    [self.passButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.view.mas_bottom).mas_equalTo(-30);
        make.right.equalTo(self.view.mas_centerX).mas_offset(-10);
        make.width.mas_equalTo(140 * kScaleWidth);
        make.height.mas_equalTo(40 * kScaleHeight);
    }];
    
    [self.comtinueButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.view.mas_bottom).mas_equalTo(-30);
        make.left.equalTo(self.view.mas_centerX).mas_offset(10);
        make.width.mas_equalTo(140 * kScaleWidth);
        make.height.mas_equalTo(40 * kScaleHeight);
    }];
    
    [self.aScrollView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.mas_equalTo(self.view);
        make.bottom.equalTo(self.passButton.mas_top);
    }];
    
    [self.completeView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.mas_equalTo(self.aScrollView);
        make.bottom.equalTo(self.passButton.mas_top);
        make.centerX.equalTo(self.aScrollView);
    }];
    
    [self.goBackBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view.mas_top).mas_offset(35);
        make.left.equalTo(self.view.mas_left).mas_offset(15);
        make.width.mas_equalTo(35);
        make.height.mas_equalTo(35);
    }];
}

#pragma mark - Event
// 返回按钮点击方法
- (void)goBackBtnClick {
    [self.navigationController popViewControllerAnimated:YES];
}
// 上传头像按钮点击方法
- (void)updateImageBtnClick {
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    // 打开相机
    UIAlertAction* camAction = [UIAlertAction actionWithTitle:@"相机" style:UIAlertActionStyleDefault handler:^(UIAlertAction* _Nonnull action) {
        [self openCamera];
    }];
    // 打开相册
    UIAlertAction* photoAction = [UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction* _Nonnull action) {
        [self openAlbum];
    }];
    // 取消
    UIAlertAction* cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    [alertVC addAction:camAction];
    [alertVC addAction:photoAction];
    [alertVC addAction:cancelAction];
    [self presentViewController:alertVC animated:YES completion:nil];
}
// 继续按钮的点击方法
-(void)comtinueButtonClick {
    @weakify(self);
    [[self.viewModel.comtinueCommand execute:self.completeView.inputNickeName.text] subscribeNext:^(id  _Nullable x) {
        @strongify(self);
        SEGEditDetailViewController *myMaleList = [[SEGEditDetailViewController alloc] init];
        myMaleList.title = @"选择职业";
        myMaleList.recordProfessionId = [SEGProfileManager sharedManager].profile.job;
        myMaleList.editType = EditJobAndMaleType_Job; // CELL 样式为职业
        myMaleList.isFromLogin = YES; // 备注为登录时的跳转
        myMaleList.showType = EditDetailShowType_UITableView; // 展示table布局
        myMaleList.userInfo = @{@"name" : @"job"};
        myMaleList.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:myMaleList animated:YES];
    } error:^(NSError * _Nullable error) {
        [SEGAlertView showTmepMessageWithMessage:error.localizedFailureReason];
    }];
}
// 跳过按钮的点击
- (void)passButtonClick {
    @weakify(self);
    [[self.viewModel.passCommand execute:@""] subscribeNext:^(id  _Nullable x) {
        @strongify(self);
        SEGEditDetailViewController *myMaleList = [[SEGEditDetailViewController alloc] init];
        myMaleList.title = @"选择职业";
        myMaleList.recordProfessionId = [SEGProfileManager sharedManager].profile.job;
        myMaleList.editType = EditJobAndMaleType_Job; // CELL 样式为职业
        myMaleList.isFromLogin = YES; // 备注为登录时的跳转
        myMaleList.showType = EditDetailShowType_UITableView; // 展示table布局
        myMaleList.userInfo = @{@"name" : @"job"};
        myMaleList.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:myMaleList animated:YES];
    }];
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self.view endEditing:YES];
}

#pragma mark - handle Image
/**
 打开相机
 */
- (void)openCamera {
    self.imagePicker = [[SEGImagePickerManager alloc] init];
    self.imagePicker.delegate = self;
    self.imagePicker.sourceType = SEGImagePickerManagerSourceTypeCamera;
    self.imagePicker.allowsEditing = YES;
    [self.imagePicker presentImagePickerControllerWithAnimated:YES completion:nil];
}
/**
 打开相册
 */
-(void)openAlbum {
    self.imagePicker = [[SEGImagePickerManager alloc] init];
    self.imagePicker.delegate = self;
    self.imagePicker.sourceType = SEGImagePickerManagerSourceTypePhotoLibrary;
    self.imagePicker.allowsEditing = YES;
    self.imagePicker.maxImagesCount = 1;
    [self.imagePicker presentImagePickerControllerWithAnimated:YES completion:nil];
}

#pragma mark - SEGImagePickerManagerDelegate
- (void)seg_imagePickerManager:(SEGImagePickerManager *)manager didFinishPickingPhotos:(NSArray<UIImage *> *)photos assets:(NSArray<PHAsset *> *)assets isSelectOriginalPhoto:(BOOL)isSelect {
    [self.viewModel.uploadImgCommand.executing subscribeNext:^(NSNumber * _Nullable x) {
        if (x.boolValue) {
           [SVProgressHUD show];
        } else {
            [SVProgressHUD dismiss];
        }
    }];
    @weakify(self);
    [[self.viewModel.uploadImgCommand execute:photos.firstObject] subscribeNext:^(UIImage *ima) {
        @strongify(self);
        [self.completeView.updateImage.layer setMasksToBounds:YES];
        [self.completeView.updateImage.layer setCornerRadius:33];
        // 显示头像
        [self.completeView.updateImage setImage:ima forState:UIControlStateNormal];
    } error:^(NSError * _Nullable error) {
        [SEGAlertView showTmepMessageWithMessage:error.localizedDescription];
    }];
}
- (void)seg_imagePickerManagerDidCancel:(SEGImagePickerManager *)picker {
    
}

#pragma mark - UIKeyboardNotification
// 键盘即将出现
- (void)keyboardWillShowChangeFrame:(NSNotification*)notification {
    NSDictionary *info = [notification userInfo];
    CGSize kbSize = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;
    if (CGRectGetMinY(self.view.frame) < 0) {
        return;
    }
    //保证最下面的控件不被遮挡
    CGFloat bottomY = kLYScreenHeight();
    bottomY = CGRectGetMaxY(self.completeView.frame) + CGRectGetMinY(self.view.frame);
    NSTimeInterval duration = [[info objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    [UIView animateWithDuration:duration animations:^{
        self.view.transform = CGAffineTransformTranslate(CGAffineTransformIdentity, 0, -kbSize.height);
    }];
}
//  键盘即将隐藏
- (void)keyboardWillHideChangeFrame:(NSNotification *)notification {
    NSDictionary *info = [notification userInfo];
    NSTimeInterval duration = [[info objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    [UIView animateWithDuration:duration animations:^{
        self.view.transform = CGAffineTransformIdentity;
    }];
}

#pragma mark - UITextFieldDelegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    if (textField == self.completeView.inputNickeName) {
        [self.completeView.inputNickeName resignFirstResponder];
    }
    return YES;
}

#pragma mark - UITraitEnvironment
- (void)traitCollectionDidChange:(UITraitCollection *)previousTraitCollection {
    [super traitCollectionDidChange:previousTraitCollection];
    [self.passButton.layer setBorderColor:kColor_3.CGColor];
}

#pragma mark - Getter
- (SEGCompleteInfoView *)completeView {
    if (!_completeView) {
        _completeView = [[SEGCompleteInfoView alloc] init];
        _completeView.delegate = self;
        _completeView.inputNickeName.delegate = self;
        _completeView.inputNickeName.text = self.viewModel.recordNickName;
        _completeView.completeInfoLabel.text = [NSString stringWithFormat:@"完善资料可获得%@积分",self.recordCoin];
    }
    return _completeView;
}
//返回按钮
- (UIButton *)goBackBtn {
    if (!_goBackBtn) {
        _goBackBtn = [[UIButton alloc] init];
        [_goBackBtn setImage:[UIImage imageWithContentsOfFile:SEGPicName(@"back")] forState:UIControlStateNormal];
        _goBackBtn.backgroundColor = [UIColor clearColor];
        [_goBackBtn addTarget:self action:@selector(goBackBtnClick) forControlEvents:UIControlEventTouchUpInside];
    }
    return _goBackBtn;
}
- (UIButton *)passButton {
    if (!_passButton) {
        _passButton = [[UIButton alloc] init];
        _passButton.backgroundColor = kColor_W;
        [_passButton setTitle:@"跳过" forState:UIControlStateNormal];
        [_passButton addTarget:self action:@selector(passButtonClick) forControlEvents:UIControlEventTouchUpInside];
        [_passButton setTitleColor:kColor_3 forState:UIControlStateNormal];
        _passButton.titleLabel.font = [UIFont systemFontOfSize:16];
        [_passButton.layer setBorderColor:kColor_3.CGColor];
        [_passButton.layer setBorderWidth:0.5];
        [_passButton.layer setMasksToBounds:YES];
        [_passButton.layer setCornerRadius:2];
    }
    return _passButton;
}
- (UIButton *)comtinueButton {
    if (!_comtinueButton) {
        _comtinueButton = [[UIButton alloc] init];
        _comtinueButton.backgroundColor = kColor_T;
        [_comtinueButton setTitle:@"继续" forState:UIControlStateNormal];
        [_comtinueButton setBackgroundImage:[UIImage imageWithColor:kColor_T] forState:UIControlStateNormal];
        [_comtinueButton setBackgroundImage:[UIImage imageWithColor:kColor_T_Press] forState:UIControlStateHighlighted];
        [_comtinueButton addTarget:self action:@selector(comtinueButtonClick) forControlEvents:UIControlEventTouchUpInside];
        [_comtinueButton setTitleColor:kColor_W forState:UIControlStateNormal];
        _comtinueButton.titleLabel.font = [UIFont systemFontOfSize:16];
        [_comtinueButton.layer setCornerRadius:2];
        [_passButton.layer setMasksToBounds:YES];
    }
    return _comtinueButton;
}
- (SEGCompletePesonalInfoViewModel *)viewModel {
    if (!_viewModel) _viewModel = [SEGCompletePesonalInfoViewModel new];
    return _viewModel;
}

@end
